package com.app.miwawa.ext.task;

import java.io.File;
import java.util.List;
import java.util.Map;

import org.framework.common.ext.util.AntSqlUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * SaaS端计划任务
 * <p>描述:自动终止合同，启动续约合同，删除无效合同</p>
 * <p>Company: Professional</p>
 * @author chanlong(陈龙)
 * @date 2016年6月12日 下午4:24:08
 * @version 1.0.2016
 */
@Component
public class Schedule {
	
	@Autowired
	private JdbcTemplate jdbc;
	
	
	
	/**
	 * 执行计划任务.
	 * @author Administrator(陈龙)
	 * @date 2016年9月5日 下午5:09:47
	 */
	//@Scheduled(cron="*/20 * * * * ?") // 每20秒执行一次  */n 代表每隔 n 秒执行一次 
	@Scheduled(cron="0 0 1 * * ?")//每天凌晨1点执行一次
	public void handlerContract(){
		String dbnameSql = "select `a`.dbname from miwawa.tb_system_center a left join `information_schema`.`SCHEMATA` b on a.dbname = `b`.`SCHEMA_NAME` where `a`.`status` = '0' and `a`.`invalid` = 'F' and `b`.`SCHEMA_NAME` is not null order by `a`.`dbname`";
		List<Map<String, Object>> list = jdbc.queryForList(dbnameSql);
		for (Map<String, Object> map : list) {
			Object dbname = map.get("dbname");
			jdbc.update("call "+dbname+".pro_base_schedule()");
		}
	}
	
	@SuppressWarnings("resource")
	public static void main(String[] args) {
		ApplicationContext context =  new ClassPathXmlApplicationContext("/config/spring/beans.xml");
		JdbcTemplate jdbc = (JdbcTemplate)context.getBean("jdbc");
		String dbnameSql = "select `a`.dbname from miwawa.tb_system_center a left join `information_schema`.`SCHEMATA` b on a.dbname = `b`.`SCHEMA_NAME` where `a`.`status` = '0' and `a`.`invalid` = 'F' and `b`.`SCHEMA_NAME` is not null order by `a`.`dbname`";
		List<Map<String, Object>> list = jdbc.queryForList(dbnameSql);
		Long startTime = System.currentTimeMillis()/1000;
		for (Map<String, Object> map : list) {
			Long start = System.currentTimeMillis()/1000;
			Object dbname = map.get("dbname");
			if("miwawa_blank".equals(dbname) || "miwawa_0test".equals(dbname)){
				continue;
			}
			AntSqlUtil.execute("/config/properties/db.properties", String.valueOf(dbname), new File("D:\\sql\\dataTransmissionUpdate.sql"));
			Long end = System.currentTimeMillis()/1000;
			System.out.println(String.valueOf(dbname));
			System.out.println(dbname+"视图及存储过程已修改，耗时 ："+(end - start)+"秒");
		}
		Long endTime = System.currentTimeMillis()/1000; 
		System.out.println("总计耗时 : "+(endTime - startTime) +"秒");
	}

}
